package com.sugar.real.estate.module.business.service.userfollow;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.sugar.real.estate.framework.common.pojo.PageResult;
import com.sugar.real.estate.module.business.controller.admin.userfollow.vo.UserFollowPageReqVO;
import com.sugar.real.estate.module.business.controller.admin.userfollow.vo.UserFollowRespVO;
import com.sugar.real.estate.module.business.controller.app.apartment.vo.AppApartmentSimpleRespVO;
import com.sugar.real.estate.module.business.controller.app.readyhouse.vo.AppReadyHouseSimpleRespVO;
import com.sugar.real.estate.module.business.controller.app.userfollow.vo.AppUserFollowPageReqVO;
import com.sugar.real.estate.module.business.controller.app.userfollow.vo.AppUserFollowSaveReqVO;
import com.sugar.real.estate.module.business.dal.dataobject.userfollow.UserFollowDO;
import com.sugar.real.estate.module.business.dal.mysql.apartment.ApartmentMapper;
import com.sugar.real.estate.module.business.dal.mysql.readyhouse.ReadyHouseMapper;
import com.sugar.real.estate.module.business.dal.mysql.userfollow.UserFollowMapper;
import com.sugar.real.estate.module.business.service.dicttype.BizDictTypeService;
import com.sugar.real.estate.module.business.util.I18nUtil;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

import static com.sugar.real.estate.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.sugar.real.estate.module.business.enums.ErrorCodeConstants.*;

/**
 * 用户关注 Service 实现类
 *
 * @author Ysugar
 */
@Service
@Validated
public class UserFollowServiceImpl implements UserFollowService {

    @Resource
    private UserFollowMapper userFollowMapper;
    @Resource
    private ApartmentMapper apartmentMapper;
    @Resource
    private ReadyHouseMapper readyHouseMapper;
    @Resource
    private BizDictTypeService dictTypeService;

    @Override
    public void deleteUserFollow(Long id) {
        // 校验存在
        validateUserFollowExists(id);
        // 删除
        userFollowMapper.deleteById(id);
    }

    @Override
    public void deleteUserFollowListByIds(List<Long> ids) {
        // 校验存在
        validateUserFollowExists(ids);
        // 删除
        userFollowMapper.deleteByIds(ids);
    }

    private void validateUserFollowExists(List<Long> ids) {
        List<UserFollowDO> list = userFollowMapper.selectByIds(ids);
        if (CollUtil.isEmpty(list) || list.size() != ids.size()) {
            throw exception(USER_FOLLOW_NOT_EXISTS);
        }
    }

    private void validateUserFollowExists(Long id) {
        if (userFollowMapper.selectById(id) == null) {
            throw exception(USER_FOLLOW_NOT_EXISTS);
        }
    }

    @Override
    public UserFollowDO getUserFollow(Long id) {
        return userFollowMapper.selectById(id);
    }

    @Override
    public PageResult<UserFollowRespVO> getUserFollowPage(UserFollowPageReqVO reqVO) {
        LocalDateTime[] createTime = reqVO.getCreateTime();
        LocalDateTime startTime = null;
        LocalDateTime endTime = null;
        if (Objects.nonNull(createTime) && createTime.length == 2) {
            startTime = createTime[0];
            endTime = createTime[1];
        }
        Long count = userFollowMapper.selectPageCount(reqVO.getUserId(), reqVO.getFollowId(), reqVO.getType(), startTime, endTime);
        if (count > 0) {
            Integer pageNo = reqVO.getPageNo();
            Integer pageSize = reqVO.getPageSize();

            int skipCount = (pageNo - 1) * pageSize;

            List<UserFollowRespVO> dataList = userFollowMapper.selectCustomPage(reqVO.getUserId(),
                    reqVO.getFollowId(), reqVO.getType(),
                    startTime, endTime,
                    skipCount, pageSize);

            return new PageResult<>(dataList, count);
        }
        return new PageResult<>(Collections.emptyList(), 0L);
    }

    @Override
    public void createUserFollow(AppUserFollowSaveReqVO createReqVO, Long userId) {
        Long followId = createReqVO.getFollowId();
        Boolean type = createReqVO.getType();

        // 判断用户是否关注
        UserFollowDO dbUserFollow = userFollowMapper.selectOne(Wrappers.<UserFollowDO>lambdaQuery()
                .eq(UserFollowDO::getUserId, userId)
                .eq(UserFollowDO::getType, type)
                .eq(UserFollowDO::getFollowId, followId));

        if (Objects.isNull(dbUserFollow)) {
            // 判断楼房是否存在
            if (type) {
                if (Objects.isNull(readyHouseMapper.selectById(followId)))
                    throw exception(APARTMENT_NOT_EXISTS, I18nUtil.getMessage("APARTMENT_NOT_EXISTS"));
            } else {
                if (Objects.isNull(apartmentMapper.selectById(followId)))
                    throw exception(READY_HOUSE_NOT_EXISTS, I18nUtil.getMessage("READY_HOUSE_NOT_EXISTS"));
            }

            UserFollowDO userFollowDO = new UserFollowDO();
            userFollowDO.setUserId(userId).setType(type).setFollowId(followId);
            userFollowMapper.insert(userFollowDO);
        } else {
            if (!dbUserFollow.getUserId().equals(userId))
                throw exception(NO_PERMISSION, I18nUtil.getMessage("NO_PERMISSION"));

            userFollowMapper.deleteById(dbUserFollow.getId());
        }
    }

    @Override
    public PageResult<?> appGetUserFollowPage(AppUserFollowPageReqVO pageReqVO, Long userId) {
        boolean chinese = I18nUtil.isChinese();

        if (Objects.nonNull(pageReqVO.getType()) && pageReqVO.getType()) {
            PageResult<AppReadyHouseSimpleRespVO> pageResult = userFollowMapper.appGetUserFollowType1Page(pageReqVO, userId);

            for (AppReadyHouseSimpleRespVO respVO : pageResult.getList()) {
                respVO.setShowImage(respVO.getShowImages().get(0))
                        .setName(I18nUtil.getMessage(respVO, "getName"))
                        .setTags(chinese ? respVO.getTagsZhCn() : respVO.getTagsEnUs())
                        .setProjectTypeName(dictTypeService.appGetAllDictDataLabel(2L, respVO.getProjectType()));
            }

            return pageResult;
        } else {
            PageResult<AppApartmentSimpleRespVO> pageResult = userFollowMapper.appGetUserFollowType0Page(pageReqVO, userId);

            for (AppApartmentSimpleRespVO respVO : pageResult.getList()) {
                respVO.setShowImage(respVO.getShowImages().get(0))
                        .setName(I18nUtil.getMessage(respVO, "getName"))
                        .setTags(chinese ? respVO.getTagsZhCn() : respVO.getTagsEnUs())
                        .setProjectLight(chinese ? respVO.getProjectLightZhCn() : respVO.getProjectLightEnUs())
                        .setProjectTypeName(dictTypeService.appGetAllDictDataLabel(2L, respVO.getProjectType()));
            }

            return pageResult;
        }

    }
}